﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace Stala
{
	class SimpleVersionFinder : IVersionFinder<Version>
	{
		public Uri VersionSource { get; set; }

		public SimpleVersionFinder(Uri versionSource)
		{
			this.VersionSource = versionSource;
		}

		public void FindLatestVersion()
		{
			if (VersionSource.IsFile)
			{
				var version = new Version(File.OpenText(VersionSource.AbsolutePath).ReadLine());
				NotifyLatestVersion(version);
			}
			else
			{
				var versionRequest = HttpWebRequest.Create(VersionSource);
				var versionResponse = (HttpWebResponse)versionRequest.GetResponse();

				var stream = versionResponse.GetResponseStream();
				var encoding = Encoding.GetEncoding("utf-8");

				var streamReader = new StreamReader(stream, encoding);
				var content = streamReader.ReadLine();
				versionResponse.Close();

				var version = new Version(content);
				NotifyLatestVersion(version);
			}
		}

		private void NotifyLatestVersion(Version version)
		{
			if (LatestVersionFound != null)
			{
				LatestVersionFound(version);
			}
		}

		public event Action<Version> LatestVersionFound;

		public event Action<string> NoVersionFound;
	}
}
